/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package service;

import entities.Note;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.QueryParam;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.WebApplicationException;
import javax.persistence.NoResultException;
import javax.persistence.EntityManager;
import converter.NoteConverter;
import java.util.Date;
import javax.ejb.Stateless;
import javax.ws.rs.POST;
import javax.ws.rs.core.Response;

/**
 *
 * @author Alex
 */

@Stateless
public class NoteResource {
    @Context
    protected UriInfo uriInfo;
    protected EntityManager em;
    protected Long id;
  
    /** Creates a new instance of NoteResource */
    public NoteResource() {
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    /**
     * Get method for retrieving an instance of Note identified by id in XML format.
     *
     * @param id identifier for the entity
     * @return an instance of NoteConverter
     */
    @GET
    @Produces({"application/xml", "application/json"})
    public NoteConverter get(@QueryParam("expandLevel") @DefaultValue("1") int expandLevel,
                             @QueryParam("delete") @DefaultValue("false") boolean delete) {

        if (delete) {
            //delete means closing all note details
            Note n = getEntity();
            Note noteToClose = (Note)em.createQuery("SELECT e FROM Note e WHERE e.noteId = :id AND e.endDate IS NULL")
                                    .setParameter("id", n.getNoteId()).getSingleResult();
            noteToClose.setEndDate(new Date());
            em.persist(noteToClose);
            
            return new NoteConverter(noteToClose, uriInfo.getAbsolutePath(),0);
        }

        return new NoteConverter(getEntity(), uriInfo.getAbsolutePath(), expandLevel);
    }

    /**
     * Put method for updating an instance of Note identified by id using XML as the input format.
     *
     * @param id identifier for the entity
     * @param data an NoteConverter entity that is deserialized from a XML stream
     */
    @POST
    @Consumes({"application/xml", "application/json"})
    public Response put(NoteConverter data) {
        Note newNote = (Note) data.resolveEntity(em).clone();

        Date now = new Date();
        Note oldVersion = (Note) em.createQuery("SELECT e FROM Note e WHERE e.noteId = :id AND e.endDate IS NULL")
                                        .setParameter("id", id).getSingleResult();
        oldVersion.setEndDate(now);
        em.persist(oldVersion);

        //set new entity properties
        long maxId = (Long)em.createQuery("SELECT MAX(n.id) FROM Note n").getSingleResult();
        newNote.setStartDate(now);
        newNote.setEndDate(null);
        newNote.setId(maxId+1);
        newNote.setNoteId(oldVersion.getNoteId());
        em.persist(newNote);

        return Response.ok().build();
    }

    /**
     * Delete method for deleting an instance of Note identified by id.
     *
     * @param id identifier for the entity
     */
    @DELETE
    public void delete() {
        deleteEntity(getEntity());
    }

    /**
     * Returns an instance of Note identified by id.
     *
     * @param id identifier for the entity
     * @return an instance of Note
     */
    protected Note getEntity() {
        try {
            return (Note) em.createQuery("SELECT e FROM Note e where e.id = :id").setParameter("id", id).getSingleResult();
        } catch (NoResultException ex) {
            throw new WebApplicationException(new Throwable("Resource for " + uriInfo.getAbsolutePath() + " does not exist."), 404);
        }
    }

    /**
     * Updates entity using data from newEntity.
     *
     * @param entity the entity to update
     * @param newEntity the entity containing the new data
     * @return the updated entity
     */
    private Note updateEntity(Note entity, Note newEntity) {
        entity = em.merge(newEntity);
        return entity;
    }

    /**
     * Deletes the entity.
     *
     * @param entity the entity to deletle
     */
    private void deleteEntity(Note entity) {
        em.remove(entity);
    }
}
